package com.link.base.base.sms.service;

import com.link.base.sms.model.SmsAccntLine;
import com.link.base.base.sms.dao.mybatis.mapper.AccntConditionMapper;
import com.link.base.base.sms.dao.mybatis.mapper.AccntGroupingMapper;
import com.link.base.base.sms.model.*;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import com.link.base.base.sms.model.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 客户分组 Service 实现类
 *
 * @Author: liulu
 * @Date:15:37 2018/11/5
 */
@Service
public class AccntGroupingServiceImpl extends BasicServiceImpl<AccntGrouping> implements AccntGroupingService {

    @Resource
    private AccntGroupingMapper accntGroupingMapper;
    @Resource
    private AccntConditionMapper accntConditionMapper;

    @Override
    public BasicMapper<AccntGrouping> getBasicMapper() {
        return accntGroupingMapper;
    }

    /**
     * @author liulu
     * @zhushi: 添加分组之后添加客户或条件
     */
    @Override
    public void afterInsert(AccntGrouping entity) throws Exception {
        if (entity.getAccntConditionList() != null && entity.getAccntConditionList().size() != 0) {
            for (AccntCondition it : entity.getAccntConditionList()) {
                it.setId(keyGenerateService.keyGenerate());
                it.setGroupingId(entity.getId());
                accntConditionMapper.insert(it);
            }
        }
        if (entity.getAccountList() != null && entity.getAccountList().size() != 0) {
            AccntGroupingIntermediate ac;
            for (SmsAccntLine iu : entity.getAccountList()) {
                Map<String, String> map = new HashMap<>(5);
                map.put("id", keyGenerateService.keyGenerate().toString());
                map.put("accoutId", iu.getId().toString());
                map.put("groupingId", entity.getId().toString());
                ac = new AccntGroupingIntermediate(keyGenerateService.keyGenerate(), iu.getId(), entity.getId());
                accntGroupingMapper.inAccntGroupingInsert(ac);
            }
        }

    }

    @Override
    public QueryParams analysisCondition(AccntGrouping entity) {

        QueryParams qps = new QueryParams();
        qps.setPageFlag(entity.getPageFlag());
        qps.setPage(entity.getPage());
        qps.setTotalFlag(entity.getTotalFlag());
        qps.setRows(entity.getRows());
        qps.setTotal(entity.getTotal());

        List<AccntCondition> cond = entity.getAccntConditionList();
        if (!CollectionUtils.isEmpty(cond)) {
            for (AccntCondition accntCondition : cond) {
                switch (accntCondition.getConditionType()) {
                    case "Events":
                        if (StringUtils.equals(accntCondition.getOperator(), "Include")) {
                            accntCondition.setOperator(Filter.OP_LESS_THEN);
                        }
                        if (StringUtils.equals(accntCondition.getOperator(), "Exclude")) {
                            accntCondition.setOperator(Filter.OP_GREAT_EQUAL);
                        }
                        //时间转化
                        int i = accntCondition.getValue().lastIndexOf(",") + 1;
                        accntCondition.setValue(accntCondition.getValue().substring(i));
                        String teme = this.setTime(Integer.parseInt(accntCondition.getValue()));
                        accntCondition.setValue(teme);
                        switch (accntCondition.getSubtype()) {
                            case "Consuming":
                                qps.addFilter(new Filter("xAttr31", "xAttr31", accntCondition.getOperator(), accntCondition.getValue()));
                                break;
                            case "Visit":
                                qps.addFilter(new Filter("xAttr32", "xAttr32", accntCondition.getOperator(), accntCondition.getValue()));
                                break;
                            case "WeChatMessage":
                                qps.addFilter(new Filter("xAttr33", "xAttr33", accntCondition.getOperator(), accntCondition.getValue()));
                                break;
                            case "OnlineCamp":
                                qps.addFilter(new Filter("xAttr34", "xAttr34", accntCondition.getOperator(), accntCondition.getValue()));
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        if (StringUtils.equals(accntCondition.getOperator(), "Include")) {
                            accntCondition.setOperator(Filter.OP_IN);
                        } else {
                            accntCondition.setOperator(Filter.OP_NOT_IN);
                        }
                        qps.addFilter(new Filter(accntCondition.getProperty(),
                                accntCondition.getProperty(), accntCondition.getOperator(), "[" + accntCondition.getValue() + "]"));
                        break;
                }
            }
        }
        return qps;
    }

    @Override
    public void analysisConditionWithoutQps(AccntGrouping accntGrouping, SmsAccntLineDTO smsAccntLineDTO) {
        List<AccntCondition> conditions = accntGrouping.getAccntConditionList();
        List<SmsParamTable> smsParamTableList = new ArrayList<>();
        if (conditions.isEmpty()) {
            return;
        }
        conditions.forEach(e -> {
            String conditionType = e.getConditionType();
            String subtype = e.getSubtype();
            String property = e.getProperty();
            String operator = switchOperator(e.getOperator(), conditionType);;
            String value = e.getValue();
            SmsParamTable smsParamTable;
            switch (conditionType) {
                case "Events":
                    int i = value.lastIndexOf(",") + 1;
                    String subStr = value.substring(i);
                    String time = setTime(Integer.parseInt(subStr));
                    switch (subtype) {
                        case "Consuming":
                            smsParamTable = new SmsParamTable("lnk_sale_order", "row_id", "acct_id", "created", operator, time,true);
                            smsParamTableList.add(smsParamTable);
                            break;
                        case "Visit":
                            smsParamTable = new SmsParamTable("lnk_opty", "row_id", "accnt_id", "created", operator, time,true);
                            smsParamTableList.add(smsParamTable);
                            break;
                        case "WeChatMessage":
                            smsParamTable = new SmsParamTable("LNK_WX_RESULT", "WX_OWN_OPEN_ID", "FROM_USER", "SEND_DATE", operator, time,true);
                            smsParamTableList.add(smsParamTable);
                            break;
                        case "OnlineCamp":
                            smsParamTable = new SmsParamTable("LNK_INNER_ACT_ACCNT", "row_id", "accnt_id", "RAFFLE_TIME", operator, time, true);
                            smsParamTableList.add(smsParamTable);
                            break;
                        default:
                            break;
                    }
                    break;
                case "CustomerTags":
                    String conditionStr = spliceConditionStr(value);
                    smsParamTable = new SmsParamTable("lnk_inter_accnt_tag", "row_id", "accnt_row_id", "tag_id", operator, conditionStr);
                    smsParamTableList.add(smsParamTable);
                    break;
                case "CustomerAttribute":
                    QueryParams qps = new QueryParams();
                    Filter customAttrFilter = new Filter(property, operator, "[" + value + "]");
                    qps.addFilter(customAttrFilter);
                    BasicModel.transformClass(smsAccntLineDTO, qps);
                    break;
                default:
                    break;
            }
        });
        smsAccntLineDTO.setSmsParamTableList(smsParamTableList);
    }

    public String setTime(int time) {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.DATE, -time);
        str = sdf.format(lastDate.getTime());
        return str;
    }

    /**
     * 转换操作符
     *
     * @author 曲元涛
     * @date 2019/4/25 19:09
     * @param op 当前操作符
     * @param conditionType 条件类型
     */
    private String switchOperator(String op, String conditionType) {
        switch (op) {
            case "Include":
                switch (conditionType) {
                    case "Events":
                        op = Filter.OP_LESS_THEN;
                        break;
                    case "CustomerTags":
                    case "CustomerAttribute":
                        op = Filter.OP_IN;
                        break;
                    default:
                        throw new ServiceException("SMS-001", conditionType);
                }
                break;
            case "Exclude":
                switch (conditionType) {
                    case "Events":
                        op = Filter.OP_GREAT_EQUAL;
                        break;
                    case "CustomerTags":
                    case "CustomerAttribute":
                        op = Filter.OP_NOT_IN;
                        break;
                    default:
                        throw new ServiceException("SMS-001", conditionType);
                }
                break;
            default:
                throw new ServiceException("SMS-001", op);
        }
        return op;
    }

    /**
     * 拼接字符串 eg:('aaa','bbb','ccc')
     *
     * @author 曲元涛
     * @date 2019/4/25 19:11
     * @param value 逗号间隔的字符串
     */
    private String spliceConditionStr(String value) {
        String[] arr = value.split(",");
        StringBuilder builder = new StringBuilder("(");
        for (String s : arr) {
            builder.append("'").append(s).append("'").append(",");
        }
        builder.deleteCharAt(builder.lastIndexOf(","));
        builder.append(")");
        return builder.toString();
    }
}
